#include "Buffer.h"

#include <sys/uio.h>

ssize_t Buffer::readFd(int fd, int *saveError)
{

    char stackBuff[65536] = {0};

    size_t writeBytes = writableBytes();
    // iovec作用：
    // 先存vec[0]，不够在用vec[1]，相当于存入不连续的空间
    struct iovec vec[2];
    vec[0].iov_base = beginWrite();
    vec[0].iov_len = writeBytes;

    vec[1].iov_base = stackBuff;
    vec[1].iov_len = sizeof stackBuff;

    // 固定写法
    const int iovcnt = (writeBytes < sizeof stackBuff) ? 2 : 1;
    const ssize_t n = ::readv(fd, vec, iovcnt);
    if (n < 0)
    {
        *saveError = errno;
    }
    else if (n <= writeBytes)
    {
        // 够用
        writeIndex_ += n;
    }
    else
    {
        // 不够用, 这里已经写满写区了
        writeIndex_ = buffer_.size();
        append(stackBuff, n - writeBytes);
    }
    return n;
}

ssize_t Buffer::writeFd(int fd, int *saveError)
{
    struct iovec vec;
    vec.iov_base = (void*)peek();
    vec.iov_len = readableBytes();
    ssize_t n = ::writev(fd, &vec, 1);
    if (n < 0)
    {
        *saveError = errno;
    }
    return n;
}